﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;

namespace CSS.Action.Core
{
    public abstract class ModuleRequestBase : IHttpHandler, IRequiresSessionState
    {
        public delegate void ProcessRequestDelegate(HttpContext ctx);

        #region process

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.AddHeader("Accept-Encoding", "gzip, deflate");
            var actionName = !string.IsNullOrEmpty(context.Request.Form["m"])
                                 ? context.Request.Form["m"].Trim().ToLower()
                                 : "file";
            if (string.IsNullOrEmpty(actionName))
            {
                context.Response.Status = "404 not found";
                context.Server.Transfer("/404.aspx");
                context.Response.End();
                return;
            }
            var action = GetAction(actionName);
            if (action != null)
            {
                action.Do(context);
            }
        }

        #endregion

        #region ###

        public enum ActionGroup
        {
            ModuleAction = 1,
            CoreLibAction = 2
        }

        // Fields
        private static readonly IDictionary<string, ActionBase> Dicts = new Dictionary<string, ActionBase>();

        protected static void RegisterAction(string actionName, ActionBase action)
        {
            Dicts[actionName] = action;
        }

        protected static ActionBase GetAction(string actionName)
        {
            ActionBase action;
            return Dicts.TryGetValue(actionName, out action) ? action : null;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        #endregion
    }
}
